package com.liqi.web.controller.openapi.middleware;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.liqi.common.core.controller.BaseController;
import com.liqi.common.core.domain.AjaxResult;
import com.liqi.common.core.domain.R;
import com.liqi.common.utils.StringUtils;
import com.liqi.deployment.domain.DvDeployment;
import com.liqi.deployment.service.IDvDeploymentService;
import com.liqi.monitor.domain.DvUpdatePlan;
import com.liqi.monitor.domain.dto.DeviceInfoDto;
import com.liqi.monitor.domain.dto.UpdateResultDto;
import com.liqi.monitor.service.DvUpdatePlanService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: lgh
 * @Date: 2022-10-31
 * @Description: 更新结果上报接口
 */
@Api(tags = "提供给中间件的接口")
@RestController
@RequestMapping("/openApi/middleware")
public class UpdatePlanController extends BaseController {

    @Autowired
    private DvUpdatePlanService dvUpdatePlanService;


    @Autowired
    private IDvDeploymentService deploymentService;

    @PostMapping("/saveUpdateSoftwareResult")
    @ApiOperation("更新结果上报接口")
    public R saveUpdateSoftwareResult(@Validated @RequestBody UpdateResultDto resultDto ){
        DvDeployment deployment = deploymentService.getByDeviceId(resultDto.getDeviceId());
        if (deployment == null) {
            return R.fail("找不到当前设备。deviceId=" + resultDto.getDeviceId());
        }
        dvUpdatePlanService.saveUpdateSoftwareResult(resultDto);
        return R.ok("结果上报成功");
    }

    @PostMapping("/stopUpdateResult")
    @ApiOperation("终止计划上报接口")
    public R stopUpdateResult(@Validated @RequestBody DeviceInfoDto resultDto ){
        logger.info("终止计划上报接口接收中间件发送实体{}", JSON.toJSONString(resultDto));
        DvDeployment deployment = deploymentService.getByDeviceId(resultDto.getDeviceId());
        if (deployment == null) {
            return R.fail("找不到当前设备。deviceId=" + resultDto.getDeviceId());
        }
        dvUpdatePlanService.update(new UpdateWrapper<DvUpdatePlan>().set("message_code",resultDto.getMessageCode()).set("plan_status", resultDto.getPlanStatus())
                .set("error_message", resultDto.getErrorMessage())
                .eq("plan_id", resultDto.getPlanId()).eq("device_id", resultDto.getDeviceId()));
        return R.ok("终止计划上报成功");
    }
}
